// pages/home/home.js
const app = getApp()

Page({
  data: {
    // 设备连接状态
    isConnected: false,
    
    // 音频数据
    soundLevel: 0,
    soundType: 'normal',
    soundAlert: false,
    
    // 界面状态
    showAlert: false,
    alertMessage: '',
    lastUpdateTime: '',
    
    // 报警统计
    todayAlarmCount: 0,
    unhandledAlarmCount: 0
  },

  onLoad(options) {
    console.log('首页加载')
    
    // 初始化数据
    this.initData()
    
    // 初始化MQTT连接
    this.initMQTTConnection()
    
    // 加载报警统计
    this.loadAlarmStatistics()
    
    // 定时更新数据
    this.startDataUpdate()
  },

  onShow() {
    console.log('首页显示')
    
    // 刷新数据
    this.refreshData()
    
    // 刷新报警统计
    this.loadAlarmStatistics()
  },

  onHide() {
    console.log('首页隐藏')
    
    // 清除定时器
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
      this.updateTimer = null
    }
  },

  onUnload() {
    console.log('首页卸载')
    
    // 清除定时器
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
      this.updateTimer = null
    }
  },

  /**
   * 初始化数据
   */
  initData() {
    // 从全局数据中获取初始状态
    const globalData = app.globalData
    
    this.setData({
      isConnected: globalData.deviceStatus.isConnected,
      soundLevel: globalData.audioData.soundLevel,
      soundType: globalData.audioData.soundType,
      soundAlert: globalData.audioData.alert,
      lastUpdateTime: this.formatTime(globalData.audioData.timestamp)
    })
  },

  /**
   * 初始化MQTT连接
   */
  initMQTTConnection() {
    console.log('MQTT连接已暂时禁用，使用模拟数据')
    // 直接启动模拟数据
    this.startMockData()
    
    /* 
    // 原MQTT连接代码（暂时注释）
    const mqttManager = app.getMQTTManager()
    
    // 如果未连接，尝试连接
    if (!app.globalData.mqttConnected) {
      mqttManager.connect()
        .then(() => {
          console.log('MQTT连接成功')
          wx.showToast({
            title: '设备连接成功',
            icon: 'success'
          })
        })
        .catch(error => {
          console.log('MQTT连接失败:', error)
          // 在开发阶段，MQTT连接失败是正常的
          // 可以使用模拟数据进行测试
          this.startMockData()
        })
    }
    */
  },

  /**
   * 启动模拟数据（用于开发测试）
   */
  startMockData() {
    console.log('启动模拟数据')
    
    // 模拟设备连接
    setTimeout(() => {
      this.setData({
        isConnected: true
      })
      app.globalData.deviceStatus.isConnected = true
    }, 2000)
    
    // 模拟音频数据更新
    setInterval(() => {
      const mockLevel = 30 + Math.random() * 40 // 30-70dB
      const isAlert = mockLevel > 60
      
      this.setData({
        soundLevel: Math.round(mockLevel),
        soundAlert: isAlert,
        lastUpdateTime: this.formatTime(Date.now())
      })
      
      // 更新全局数据
      app.globalData.audioData = {
        soundLevel: Math.round(mockLevel),
        soundType: isAlert ? 'loud' : 'normal',
        alert: isAlert,
        confidence: 0.8,
        timestamp: Date.now()
      }
      
      // 如果声音过大，创建报警记录
      if (isAlert && Math.random() > 0.7) {
        this.createMockAlarm()
      }
      
    }, 3000)
  },

  /**
   * 创建模拟报警
   */
  createMockAlarm() {
    const alarmManager = app.getAlarmManager()
    const types = ['verbal_bullying', 'physical_bullying', 'suspicious']
    const levels = ['medium', 'high']
    
    const mockAlarmData = {
      type: types[Math.floor(Math.random() * types.length)],
      level: levels[Math.floor(Math.random() * levels.length)],
      decibel: this.data.soundLevel,
      deviceId: 'mock_device_001',
      latitude: 39.9042 + (Math.random() - 0.5) * 0.01,
      longitude: 116.4074 + (Math.random() - 0.5) * 0.01,
      address: '测试学校教学楼3楼302室',
      confidence: 0.8
    }
    
    const alarmRecord = alarmManager.createAlarmRecord(mockAlarmData)
    alarmManager.saveAlarmRecord(alarmRecord)
    
    // 更新统计数据
    this.loadAlarmStatistics()
    
    console.log('创建模拟报警:', alarmRecord)
  },

  /**
   * 加载报警统计
   */
  async loadAlarmStatistics() {
    try {
      // 检查是否已登录
      const authManager = require('../../utils/auth.js')
      if (!authManager.isLoggedIn) {
        return
      }
      
      const api = require('../../utils/api.js')
      const result = await api.alarm.getStatistics({
        userId: authManager.userInfo.userId,
        timeRange: 'today'
      })
      
      if (result.code === 200) {
        const stats = result.data
        this.setData({
          todayAlarmCount: stats.todayCount || 0,
          unhandledAlarmCount: stats.unhandledCount || 0
        })
      }
    } catch (error) {
      console.error('获取报警统计失败:', error)
      // 使用本地数据作为备用
      const alarmManager = app.getAlarmManager()
      
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const todayStart = today.getTime()
      const todayEnd = todayStart + 24 * 60 * 60 * 1000
      
      const todayAlarms = alarmManager.getAlarmsByTimeRange(todayStart, todayEnd)
      const unhandledAlarms = alarmManager.getUnhandledAlarms()
      
      this.setData({
        todayAlarmCount: todayAlarms.length,
        unhandledAlarmCount: unhandledAlarms.length
      })
    }
  },

  /**
   * 开始数据更新
   */
  startDataUpdate() {
    // 每5秒更新一次界面
    this.updateTimer = setInterval(() => {
      this.refreshData()
    }, 5000)
  },

  /**
   * 刷新数据
   */
  refreshData() {
    const globalData = app.globalData
    
    this.setData({
      isConnected: globalData.deviceStatus.isConnected,
      soundLevel: globalData.audioData.soundLevel,
      soundType: globalData.audioData.soundType,
      soundAlert: globalData.audioData.alert,
      lastUpdateTime: this.formatTime(globalData.audioData.timestamp)
    })
  },

  /**
   * MQTT状态变化回调
   */
  onMQTTStatusChange(data) {
    console.log('首页收到MQTT状态变化:', data)
    this.setData({
      isConnected: data.connected
    })
  },

  /**
   * 新报警回调
   */
  onNewAlarm(alarmRecord) {
    console.log('首页收到新报警:', alarmRecord)
    
    // 更新统计
    this.loadAlarmStatistics()
    
    // 显示报警提示
    this.setData({
      showAlert: true,
      alertMessage: `检测到${this.getAlarmTypeName(alarmRecord.type)}，是否立即处理？`
    })
  },

  /**
   * 设备状态变化回调
   */
  onDeviceStatusChange(status) {
    console.log('首页收到设备状态变化:', status)
    this.setData({
      isConnected: status.online || false
    })
  },

  /**
   * 音频数据更新回调
   */
  onAudioDataUpdate(data) {
    console.log('首页收到音频数据更新:', data)
    this.setData({
      soundLevel: data.decibel || 0,
      soundAlert: data.alert || false,
      lastUpdateTime: this.formatTime(Date.now())
    })
  },

  /**
   * 紧急报警按钮
   */
  emergencyCall() {
    // 检查登录状态
    const authManager = require('../../utils/auth.js')
    if (!authManager.requireLogin() || !authManager.requireBind()) {
      return
    }
    
    wx.showModal({
      title: '确认报警',
      content: '确定要发送紧急报警吗？这将通知相关人员立即处理。',
      confirmText: '确认报警',
      confirmColor: '#ee0a24',
      success: (res) => {
        if (res.confirm) {
          // 跳转到报警提交页面
          wx.navigateTo({
            url: '/pages/alarm-submit/alarm-submit?emergency=true'
          })
        }
      }
    })
  },

  /**
   * 手动报警
   */
  manualAlarm() {
    // 检查登录状态
    const authManager = require('../../utils/auth.js')
    if (!authManager.requireLogin() || !authManager.requireBind()) {
      return
    }
    
    // 跳转到报警提交页面
    wx.navigateTo({
      url: '/pages/alarm-submit/alarm-submit'
    })
  },

  /**
   * 查看报警历史
   */
  viewAlarmHistory() {
    // 检查登录状态
    const authManager = require('../../utils/auth.js')
    if (!authManager.requireLogin()) {
      return
    }
    
    wx.navigateTo({
      url: '/pages/alarm-history/alarm-history'
    })
  },

  /**
   * 发送紧急报警
   */
  sendEmergencyAlarm() {
    const alarmManager = app.getAlarmManager()
    
    // 获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const emergencyData = {
          type: 'emergency',
          level: 'critical',
          latitude: res.latitude,
          longitude: res.longitude,
          accuracy: res.accuracy,
          address: '手动报警',
          deviceId: 'manual_alarm',
          decibel: this.data.soundLevel,
          confidence: 1.0
        }
        
        // 创建报警记录
        const alarmRecord = alarmManager.createAlarmRecord(emergencyData)
        alarmManager.saveAlarmRecord(alarmRecord)
        
        // TODO: 当MQTT配置好后，取消注释以下代码发送到硬件设备
        /*
        const mqttManager = app.getMQTTManager()
        mqttManager.sendCommand('emergency_alarm', {
          alarmId: alarmRecord.id,
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          timestamp: Date.now()
        })
        */
        
        // 更新统计
        this.loadAlarmStatistics()
        
        wx.showToast({
          title: '报警已发送',
          icon: 'success'
        })
        
        console.log('紧急报警已发送:', alarmRecord)
      },
      fail: () => {
        wx.showToast({
          title: '获取位置失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 求助热线
   */
  quickHelp() {
    wx.showActionSheet({
      itemList: ['校园安全热线', '心理咨询热线', '紧急救助电话'],
      success: (res) => {
        const phones = ['400-123-4567', '400-789-0123', '110']
        const phone = phones[res.tapIndex]
        
        wx.showModal({
          title: '拨打电话',
          content: `确定要拨打 ${phone} 吗？`,
          success: (modalRes) => {
            if (modalRes.confirm) {
              wx.makePhoneCall({
                phoneNumber: phone
              })
            }
          }
        })
      }
    })
  },

  /**
   * 处理报警弹窗确认
   */
  handleAlert() {
    this.setData({
      showAlert: false
    })
    
    // 跳转到报警列表页面
    wx.navigateTo({
      url: '/pages/alarm-list/alarm-list'
    })
  },

  /**
   * 关闭报警弹窗
   */
  dismissAlert() {
    this.setData({
      showAlert: false
    })
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '暂无更新'
    
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) { // 小于1分钟
      return '刚刚更新'
    } else if (diff < 3600000) { // 小于1小时
      return `${Math.floor(diff / 60000)}分钟前`
    } else {
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  },

  /**
   * 获取报警类型名称
   */
  getAlarmTypeName(type) {
    const typeMap = {
      'verbal_bullying': '言语欺凌',
      'physical_bullying': '身体欺凌',
      'social_bullying': '社交欺凌',
      'cyber_bullying': '网络欺凌',
      'emergency': '紧急情况',
      'suspicious': '可疑活动'
    }
    return typeMap[type] || '异常情况'
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshData()
    this.loadAlarmStatistics()
    
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})